using System;
using Exceptions;

namespace FrameIdentityReq.Frames
{
    public class IntField : BitsField, IIntField
    {
        int MaxValue { get { return ~(-1 << Count); } }

        public IntField(IBytesBuffer buffer, int startAt, int count, string name)
            : base(buffer, startAt, count, name) { }

        public IntField(IField field, int count, string name)
            : base(field, count, name) { }

        public new int Value
        {
            get
            {
                int result = 0;
                foreach (var v in base.Value)
                {
                    result <<= 8;
                    result += v;
                }
                return (int)result;
            }

            set
            {
                if (value < 0 || value > MaxValue)
                    throw new ExceptionOverLength($"{Name} = {value}, 取值超出范围[0, {MaxValue}].");

                byte[] bits = new byte[(Count + 7) << 3];
                for (int i = bits.Length - 1; i >= 0; i--)
                {
                    bits[i] = (byte)(value & 0xFF);
                    value >>= 8;
                }
                base.Value = bits;
            }
        }
    }
}